<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场所名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入场所名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属辖区" prop="xqid">
        <el-cascader :props="props" @change="changeQueryXqid"></el-cascader>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="fzr">
        <el-input
          v-model="queryParams.fzr"
          placeholder="请输入负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option
            v-for="dict in dict.type.store_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="分类" prop="type">
        <el-select v-model="queryParams.type" placeholder="分类" clearable>
          <el-option
            v-for="dict in dict.type.store_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:store:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-popover
          placement="bottom"
          width="400"
          trigger="click">
          <div>
            <el-upload
              class="upload-demo"
              drag
              :action="importData"
              :headers="headers"
              :on-success="uploadSuccess"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <br>
            <el-link type="primary" :href="importTemplate">下载导入模板</el-link>
          </div>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            slot="reference"
            v-hasPermi="['system:store:import']"
          >导入</el-button>
        </el-popover>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:store:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="场所名称" align="center" prop="name" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.store_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.store_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="所属辖区" align="center" prop="xqname" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="负责人" align="center" prop="fzr" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="场所人数" align="center" prop="csnumber" />
      <el-table-column label="经度" align="center" prop="lon" />
      <el-table-column label="纬度" align="center" prop="lat" />
      <el-table-column label="创建人" align="center" prop="creatername" />
      <el-table-column label="操作人" align="center" prop="opertername" />
      <el-table-column label="操作时间" align="center" prop="operTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:store:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:store:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改九小场所基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="场所名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入场所名称" />
        </el-form-item>
        <el-form-item label="所属辖区" prop="xqid">
          <el-cascader :props="props" :placeholder="form.xqname" @change="changeXqid"></el-cascader>
        </el-form-item>
        <el-form-item label="类别" prop="type">
<!--          <el-input v-model="form.type" placeholder="请输入所属辖区" />-->

          <el-select v-model="form.type" clearable>
            <el-option
              v-for="(dict, index) in dict.type.store_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value - 0"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="门头照片" prop="address">
              <el-upload
                class="avatar-uploader"
                :headers="headers"
                :action="uploadUrl"
                :file-list="[{
                  url: form.signboard
                }]"
                :show-file-list="false"
                :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'signboard')"
                :before-upload="file => uploadBefore(file, 'signboard')">
                <img v-if="form.signboard" :src="form.signboard" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业执照" prop="address">
              <el-upload
                class="avatar-uploader"
                :headers="headers"
                :action="uploadUrl"
                :file-list="[{
              url: form.license
            }]"
                :show-file-list="false"
                :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'license')"
                :before-upload="file => uploadBefore(file, 'license')">
                <img v-if="form.license" :src="form.license" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="负责人" prop="fzr">
          <el-input v-model="form.fzr" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="场所人数" prop="csnumber">
          <el-input v-model="form.csnumber" placeholder="请输入场所人数" />
        </el-form-item>
        <el-form-item label="场所层数" prop="cengshu">
          <el-input v-model="form.cengshu" placeholder="请输入场所层数" />
        </el-form-item>
        <el-form-item label="场所面积" prop="mianji">
          <el-input v-model="form.mianji" placeholder="请输入场所面积" />
        </el-form-item>
        <el-form-item label="独立烟感数量" prop="yanganshu">
          <el-input v-model="form.yanganshu" placeholder="请输入独立烟感数量" />
        </el-form-item>
        <el-form-item label="经度" prop="lon">
          <el-input v-model="form.lon" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.store_status"
              :key="dict.value"
              :label="dict.value - 0"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="status" prop="lat">-->
<!--          <el-input v-model="form.status" placeholder="status" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="创建人" prop="creater">-->
<!--          <el-input v-model="form.creater" placeholder="请输入创建人" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="操作人" prop="operter">-->
<!--          <el-input v-model="form.operter" placeholder="请输入操作人" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="操作时间" prop="operTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.operTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择操作时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="删除标识：0正常，1删除" prop="delFlag">-->
<!--          <el-input v-model="form.delFlag" placeholder="请输入删除标识：0正常，1删除" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStore, getStore, delStore, addStore, updateStore, importTemplate, importData } from '@/api/system/store'
import {getdeptByparentid} from "@/api/system/dept";
import { getToken } from '@/utils/auth'
import {uploadUrl} from "@/api/system/config";
import store from "@/store";

export default {
  name: "Store",
  dicts: ['store_type', 'store_status'],
  data() {
    return {
      importTemplate,
      importData,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 九小场所基础信息表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        type: null,
        xqid: null,
        address: null,
        fzr: null,
        phone: null,
        csnumber: null,
        lon: null,
        lat: null,
        creater: null,
        operter: null,
        operTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      uploadUrl,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      props: {
        checkStrictly: true,
        lazy: true,
        lazyLoad (node, resolve) {
          const params = {
            parentid: ['admin', 'adm'].filter(item => store.getters.roles.includes(item)).length ? 200 : store.getters.deptId,
            deptType: '0'
          }
          console.log('node', node)
          params.parentid = node.value || (['admin', 'adm'].filter(item => store.getters.roles.includes(item)).length ? 200 : store.getters.deptId)
          const { level } = node;
          getdeptByparentid(params).then(res => {
            const nodes = res.data.map(item => {
              return {
                value: item.deptId,
                label: item.deptName,
                leaf: level >= 1
              }
            })
            resolve(nodes)
          })
        }
      }
    };
  },
  created() {
    this.getList();
    console.log('dict', this.dict.type.store_type)
  },
  methods: {
    /** 查询九小场所基础信息列表 */
    getList() {
      this.loading = true;
      listStore(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: 1,
        type: null,
        xqid: null,
        address: null,
        fzr: null,
        phone: null,
        csnumber: null,
        cenghsu: null,
        mianji: null,
        yanganshu: null,
        lon: null,
        lat: null,
        creater: null,
        createTime: null,
        operter: null,
        operTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加九小场所基础信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStore(id).then(response => {
        this.form = response.data;
        for(let i = 0; i < this.form.photoList.length; i++) {
          if (this.form.photoList[i].type === 1) {
            this.form.signboard = this.form.photoList[i].imgUrl
            this.form.signboardId = this.form.photoList[i].id
          }
          if (this.form.photoList[i].type === 2) {
            this.form.licenseId = this.form.photoList[i].id
            this.form.license = this.form.photoList[i].imgUrl
          }
        }
        this.open = true;
        this.title = "修改九小场所基础信息";
      });
    },
    uploadSuccess(res, file, fileList) {
      console.log('upres', res, file, fileList)
      this.$message({
        message: res.code === 200 ? '导入成功！' : res.msg,
        type: res.code === 200 ? 'success' : 'error'
      })
      this.getList()
    },
    changeXqid(v) {
      this.form.xqid = v[v.length - 1]
      console.log('v', v, this.form.xqid)
    },
    changeQueryXqid(v) {
      this.queryParams.pdeptId = v[v.length - 1]
      console.log('v', v, this.form.xqid)
    },
    uploadBefore(file, type) {
      console.log('file', file)
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG,PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isJPG && isLt2M;
    },
    uploadImgSuccess(res, file, fileList, type) {
      console.log('res', res.fileName)
      this.form[type] = res.fileName
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.photoList = [
            ...[
              {
                type: 1,
                imgUrl: this.form.signboard,
                id: this.form.signboardId
              }
            ],
            ...[
              {
                type: 2,
                imgUrl: this.form.license,
                id: this.form.licenseId
              }
            ]
          ]
          if (this.form.id != null) {
            updateStore(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStore(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除九小场所基础信息编号为"' + ids + '"的数据项？').then(function() {
        return delStore(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
